package com.atguigu.tingshu.order.receiver;

import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.order.mapper.OrderInfoMapper;
import com.atguigu.tingshu.order.service.MqOpsService;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.apache.commons.lang3.StringUtils;

@Component
@Slf4j
public class OrderInfoReceiver {


    @Autowired
    private MqOpsService mqOpsService;

    @Autowired
    private OrderInfoService orderInfoService;

    /**
     * 监听本地消息队列中的消息
     * 此方法通过RabbitListener注解监听特定队列中的消息，并进行处理
     *
     * @param content 消息内容，即队列中接收到的消息体
     * @param message 消息对象，包含消息的详细属性
     * @param channel AMQP通道，用于处理消息的确认
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            value = MqConst.QUEUE_LOCAL_MSG,
                            durable = "true",
                            exclusive = "false"),
            exchange = @Exchange(
                    value = MqConst.EXCHANGE_LOCAL_MSG),
                    key = MqConst.ROUTING_LOCAL_MSG))
    @SneakyThrows
    public void listenLocalMsg(String content, Message message, Channel channel) {

        // 1.获取消息，进行判断
        // 判断消息内容是否为空，如果为空则直接返回，不进行后续处理
        if (StringUtils.isEmpty(content)) {
            return;
        }
        // 2.消费消息
        // 调用服务层方法更新本地消息状态，处理业务逻辑
        mqOpsService.updateLocalMsg(content);
        // 获取消息的投递标签，用于后续的消息确认
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        // 3.手动应答
        // 手动确认消息处理成功，避免消息重复消费
        channel.basicAck(deliveryTag, false);
    }
    @RabbitListener(queues = MqConst.QUEUE_CANCEL_ORDER)
    @SneakyThrows
    public void cancelOrder(String content, Message message, Channel channel) {

        // 1.获取消息，进行判断
        if (StringUtils.isEmpty(content)) {
            return;
        }

        // 2.消费消息
        orderInfoService.cancelOrder(content);
        log.info("关闭订单完成操作");
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        // 3.手动应答
        channel.basicAck(deliveryTag, false);


    }

}